const { reminderApi } = require('../../utils/api');
const app = getApp();

Page({
  data: {
    reminders: [],
    loading: true,
    error: null,
    stats: {},
    activeTab: 'all', // all, today, medicine, glucose, exercise, diet
    filterType: '',
    showCompleted: true,
    todayCount: 0,
    refreshTrigger: 0
  },

  onLoad() {
    this.fetchData();
  },

  onShow() {
    // 每次显示页面时重新加载数据
    this.fetchData();
  },

  onPullDownRefresh() {
    this.setData({ refreshTrigger: this.data.refreshTrigger + 1 });
    this.fetchData(true);
  },

  async fetchData(showRefreshLoading = false) {
    if (showRefreshLoading) {
      wx.showNavigationBarLoading();
    } else {
      this.setData({ loading: true });
    }
    
    try {
      // 获取提醒统计信息
      const stats = await reminderApi.getReminderStats();
      
      // 根据当前tab获取提醒列表
      let reminders;
      if (this.data.activeTab === 'today') {
        reminders = await reminderApi.getTodayReminders();
      } else {
        // 获取类型过滤
        const type = this.data.activeTab === 'all' ? '' : this.data.activeTab;
        reminders = await reminderApi.getReminders(type, true);
      }
      
      // 获取今日提醒数量
      const todayReminders = await reminderApi.getTodayReminders();
      
      // 处理每个提醒的显示格式
      reminders = this.processReminders(reminders);
      
      this.setData({
        reminders,
        stats,
        todayCount: todayReminders.length,
        loading: false,
        error: null
      });
    } catch (error) {
      console.error('获取提醒数据失败', error);
      this.setData({
        loading: false,
        error: '获取提醒数据失败，请稍后重试'
      });
    } finally {
      if (showRefreshLoading) {
        wx.stopPullDownRefresh();
        wx.hideNavigationBarLoading();
      }
    }
  },

  // 处理提醒数据，添加显示格式
  processReminders(reminders) {
    if (!Array.isArray(reminders)) return [];
    
    return reminders.map(item => {
      // 格式化时间
      const timeString = `${item.hour < 10 ? '0' + item.hour : item.hour}:${item.minute < 10 ? '0' + item.minute : item.minute}`;
      
      // 格式化重复日期
      let repeatText = '';
      if (!item.repeatDays || item.repeatDays.length === 0) {
        repeatText = '不重复';
      } else if (item.repeatDays.length === 7) {
        repeatText = '每天';
      } else {
        const weekdayLabels = ['日', '一', '二', '三', '四', '五', '六'];
        const dayLabels = item.repeatDays.map(day => weekdayLabels[day]);
        repeatText = '每周 ' + dayLabels.join(', ');
      }
      
      // 返回带有格式化显示的提醒对象
      return {
        ...item,
        timeString,
        repeatText
      };
    });
  },

  handleTabChange(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
    this.fetchData();
  },

  toggleShowCompleted() {
    this.setData({ showCompleted: !this.data.showCompleted });
    this.fetchData();
  },

  navigateToDetail(e) {
    const id = e.currentTarget.dataset.id;
    
    // 验证ID是否有效
    if (!id) {
      wx.showToast({
        title: '提醒ID无效',
        icon: 'none'
      });
      return;
    }
    
    wx.navigateTo({
      url: `/pages/reminderDetail/reminderDetail?id=${id}`
    });
  },

  navigateToCreate() {
    wx.navigateTo({
      url: '/pages/reminderEdit/reminderEdit'
    });
  },

  async handleCompleteReminder(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showLoading({ title: '更新中...' });
    
    try {
      await reminderApi.completeReminder(id);
      
      // 刷新数据
      this.fetchData();
      wx.showToast({
        title: '已完成提醒',
        icon: 'success'
      });
    } catch (error) {
      console.error('完成提醒失败', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  async handleSnoozeReminder(e) {
    const id = e.currentTarget.dataset.id;
    const minutes = 30; // 默认延迟30分钟
    
    wx.showLoading({ title: '更新中...' });
    
    try {
      await reminderApi.snoozeReminder(id, minutes);
      
      // 刷新数据
      this.fetchData();
      wx.showToast({
        title: `已延迟${minutes}分钟`,
        icon: 'success'
      });
    } catch (error) {
      console.error('延迟提醒失败', error);
      wx.showToast({
        title: '操作失败，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  async handleDeleteReminder(e) {
    const id = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '确认删除',
      content: '确定删除这个提醒吗？此操作不可撤销。',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            await reminderApi.deleteReminder(id);
            
            // 刷新数据
            this.fetchData();
            wx.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } catch (error) {
            console.error('删除提醒失败', error);
            wx.showToast({
              title: '删除失败，请重试',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  }
}); 